<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.dhjob_delete"
                   @click="handleDelete">删 除
        </el-button>
        <el-button type="danger"
                   size="small"
                   icon="el-icon-download"
                   plain
                   v-if="permission.dhjob_export"
                   @click="handleExport">导 出
        </el-button>
      </template>
      //获取JSA编号
      <template slot="jsa_noForm">
        <div>
          <el-input class="jsa_no" v-model="jsaName"></el-input>
          <el-button  type="primary" icon="el-icon-plus" @click="xzjsa()" style="margin-left: 50px">选择</el-button>
        </div>
      </template>
      //获取危害措施
      <template slot="whbsForm">
        <div>
          <el-checkbox-group v-model="form1" >
            <el-checkbox v-for="wh in whbs" :label="wh.label" :key="wh.key" @change="funWh(wh.label)"></el-checkbox>
          </el-checkbox-group>
        </div>
      </template>
      //安全措施
      <template slot="aqcsForm">
        <div>
          <avue-crud :option="aqcsoption"
                     :data="aqcsdata">
            <template slot="aqcs" slot-scope="scope">
              <div style="margin-top: 11px">
                <el-col :span="20">
                  <el-input  v-model="aqcsdata[scope.row.$index].cs" width="auto"></el-input>
                </el-col>
                <avue-radio v-model="aqcsdata[scope.row.$index].state" :dic="dic" style="padding-top: 4px"></avue-radio>
              </div>
            </template>
          </avue-crud>
        </div>
      </template>
      //附件
      <template slot="scaqjdwjForm">
        <div v-if="dialogType !== 'view'">
          <el-upload
            action="/api/fileManager/upload/file"
            accept=".pdf,.mp4,.flv"
            :headers="SetHeaders"
            :file-list="fjFileList"
            :before-upload="beforeUploadKJ"
            :on-remove="handleRemoveKJ"
            :on-success="uploadKJSuccess"
          >
          <el-button type="primary">选择文件<i class="el-icon-upload el-icon--right"></i></el-button>
          </el-upload>
        </div>
      </template>
      <!-- 动火方式表格自定义 -->
      <template slot="dhfs" slot-scope="scope">
        <div>{{cellChemicals(scope.row)}}</div>
      </template>
      <!-- 申请部门 -->
      <template slot="sqbmForm">
        <div>
          <avue-input-tree default-expand-all  placeholder="请选择内容" type="tree" :dic="deptData" :props="defaultProps"></avue-input-tree>
        </div>
      </template>
      <!--作业单位名称-->
      <template slot="zydwmcForm">
        <div v-if="zylxType">
          <avue-input-tree default-expand-all v-model="zydwmc" placeholder="请选择内容" type="tree" :dic="deptData" :props="defaultProps"></avue-input-tree>
        </div>
        <div v-else>
          <avue-select v-model="zydwmc" placeholder="请选择内容" type="select" :dic="dic"></avue-select>
        </div>
      </template>
      //特殊工种证书
      <template slot="tsgzzsanForm">
        <div style="margin-left: 300px">
          <el-button
            type="primary"
            size="small"
            @click="addZS()"
            icon="el-icon-plus">
            涉及特殊工种证书
          </el-button>
        </div>
      </template>
      <!--证书-->
      <template slot="tsgzzsForm">
        <div v-if="zsData.length>1">
          <avue-crud :option="zsoption"
                     :data="zsData">
            <template slot="cz" slot-scope="scope">
              <div>
                <el-button
                  type="danger"
                  size="small"
                  @click="delZS(scope.row.$index)"
                  icon="el-icon-delete"
                >删除</el-button>
              </div>
            </template>
          </avue-crud>
        </div>
      </template>
      <!--涉及的其他特殊作业-->
      <template slot="fhypForm">
        <div>
          <el-checkbox-group v-model="fhyps" :min="1">
            <el-checkbox v-for="tszy in fhyp" :label="tszy.label" :key="tszy.key"></el-checkbox>
          </el-checkbox-group>
        </div>
      </template>
      <!--      审批人-->
      <template slot="sprForm">
        <div>
          <avue-crud :option="sproption"
                     :data="sprData">
            <template slot="sprNames" slot-scope="scope">
              <div style="margin-top: 11px">
                <avue-input v-model="sprData[scope.row.$index].sprNames" style="width: 380px" readonly></avue-input>
                <el-button type="primary" icon="el-icon-plus" @click="openChoose(scope.row.$index)" style="margin-left: 10px;">选择</el-button>
                <el-button type="danger" icon="el-icon-delete" @click="removespr(scope.row.$index)" >删除</el-button>
              </div>
            </template>
          </avue-crud>
        </div>
      </template>
    </avue-crud>
<!--    JSA弹窗-->
    <dhjobJsa
      :dhjobJsaBox="dhjobJsaBox"
      @chooseControlJsa="chooseControlJsa"
      @cancelChooseControlJsa="cancelChooseControlJsa"
      @chooseJSA="handleCloseChooseJsa"
    >
    </dhjobJsa>
    <!--特殊工种证书弹窗-->
    <chooseZS
      :chooseDialog="chooseDialog"
      :selectedZS="selectedZS"
      :zylxType="zylxType"
      @confirmChooseZS="confirmChooseZS"
      @closeChooseDialog="closeChooseDialog">
    </chooseZS>
    <!-- 弹窗：选择审批人员 -->
    <chooseApproveUser
      :chooseApproveUserDialog="chooseApproveUserDialog"
      :selectedUsers="selectedUsers"
      @confirmChooseApproveUser="confirmChooseApproveUser"
      @closeChooseApproveUserDialog="closeChooseApproveUserDialog">
    </chooseApproveUser>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove , getdhfs , getfhyp} from "@/api/xcgl/dhjob";
  import { dhjobColumn } from './constant/dhjob.js';
  import {mapGetters} from "vuex";
  import dhjobJsa from "@/views/xcgl/components/dhjobJsa";
  import chooseZS from "@/views/xcgl/components/chooseZS";
  import chooseApproveUser from "@/views/xcgl/components/chooseApproveUser";
  import {jsaColumn} from "./constant/jsa";
  import {getYjsglxList} from "../../api/xcgl/basejob";
  import {getzylxaqcs} from '@/api/xcgl/measuressetting'
  import {getDeptList} from "@/api/mmhi/major_dangerous_sources";
  import {getToken} from "@/util/auth";
  import {getspr} from "@/api/xcgl/approvalsettings";


  export default {
    components: {
      dhjobJsa,
      chooseZS,
      chooseApproveUser
    },
    data() {
      return {
        //选择审批人员
        chooseApproveUserDialog: false,
        selectedUsers: [],
        sprData: [],
        sprNo:0,
        sproption: {
          menu: false,
          addBtn: false,
          calcHeight: 30,
          tip: false,
          header: false,
          searchShowBtn: false,
          refreshBtn: false,
          searchMenuSpan: 6,
          border: true,
          index: false,
          selection: false,
          dialogClickModal: false,
          column: [{
            label: "审批步骤",
            prop: "sphj",
            align: "center",
            type: "select",
            width:250,
            dataType: "number",
            dicUrl: "/api/blade-system/dict-biz/dictionary?code=sphj",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
          },
            {
              label: "审批人",
              prop: "sprNames",
              align: "center",
              slot:true,
            }]
        },
        //涉及的其他特殊作业
        fhyp:[],
        fhyps:[],
        //特殊工种证书
        chooseDialog : false,
        selectedZS : [],
        zsData:[],
        zsoption: {
          menu: false,
          addBtn: false,
          calcHeight: 30,
          tip: false,
          header: false,
          searchShowBtn: false,
          refreshBtn: false,
          searchMenuSpan: 6,
          border: true,
          index: false,
          selection: false,
          dialogClickModal: false,
          column: [{
            label: "人员名称",
            prop: "rymc",
            align: "center",
            rules: [{
              required: true,
              message: "请输入人员名称",
              trigger: "blur"
            }]
          },
            {
              label: "作业类型",
              align: "center",
              prop: "zylx",
              type: "select",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=edu_train_archive_zylx",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dataType: "number"
            },
            {
              label: "证书编号",
              align: "center",
              prop: "zsbh"
            },
            {
              label: "操作",
              align: "center",
              prop: "cz",
              slot:true
            },
          ]
        },
        //作业单位名称
        zylxType: true,
        zydwmc: '',
        zydwlbType: {
          value: true
        },
        dic: [{
          label: '不涉及',
          value: 0
        }, {
          label: '涉及',
          value: 1
        }],
        defaultProps: {
          value: 'value', // ID字段名
          label: 'title', // 显示名称
          children: 'children' // 子级字段名
        },
        deptData:[],
        //动火方式
        cellChemicalsList: {},
        //附件上传
        SetHeaders: { "Blade-Auth": getToken() },
        fjFileList: [],
        //安全措施
        // dic:[{
        //   label:'不涉及',
        //   value:0
        // },{
        //   label:'涉及',
        //   value:1
        // }],
        aqcsdata:[],
        zylx:1,
        aqcsoption: {
          menu:false,
          addBtn:false,
          calcHeight: 30,
          tip: false,
          header: false,
          searchShowBtn:false,
          refreshBtn:false,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: false,
          dialogClickModal: false,
          column:[{
            label: "安全措施",
            prop: "aqcs",
            align: "center",
            slot:true,
          }]
        },
        //危害辨识
        form1:[],
        whbs:[],
        //JSA弹窗
        jsaId:"",
        jsaName:"",
        JSANO:false,
        dhjobJsaBox:false,
        dialogType: "",
        viewLabel: "view",
        jsaoption: {
          addBtn:false,
          calcHeight: 30,
          tip: false,
          searchMenuSpan: 6,
          refreshBtn:false,
          header:false,
          dialogClickModal: false,
          column: jsaColumn
        },
        jsaData:[],

        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          column: dhjobColumn
        },
        data: []
      };
    },

    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.dhjob_add, false),
          viewBtn: this.vaildData(this.permission.dhjob_view, false),
          delBtn: this.vaildData(this.permission.dhjob_delete, false),
          editBtn: this.vaildData(this.permission.dhjob_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    mounted(){
      this.getwhbs();
      this.getaqcs();
      this.getDept();
      this.getdhfs();
      this.getfhyp();
      this.getSPR();
    },
    watch: {
      //作业单位类别级联作业单位名称
      'form.zydwlb': {
        handler(val) {
          if (val === 1) {
            this.zylxType = true
            this.zydwmc=''
          } else {
            this.zylxType = false
            this.zydwmc=''
          }
        }
      }
    },
    methods: {
      //打开审批人弹窗
      openChoose(sprNo){
        this.chooseApproveUserDialog=true;
        this.sprNo=sprNo
      },
      // 确定选择审批人员
      confirmChooseApproveUser(userList) {
        this.approveUserData = [];
        var userName=[];
        for(let i = 0 ; i < userList.length ; i++) {
          let item = userList[i];
          let selectUser = {};
          for(var key in item) {
            selectUser[key] = item[key];
          }
          selectUser["shry"] = item.realName;
          this.approveUserData.push(selectUser);
        }
        this.approveUserData.forEach(user=>{
          userName.push(user.shry)
        })
        this.sprData[this.sprNo].sprNames=userName.join('|')
        console.log(this.sprData)
        this.closeChooseApproveUserDialog();
      },
      // 关闭、取消选择审批人员弹窗
      closeChooseApproveUserDialog() {
        this.selectedUsers = [];
        this.chooseApproveUserDialog = false;
      },
      //移除审批人
      removespr(index) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.sprData.splice(index, 1);
        });
      },
      //获取审批人
      getSPR() {
        getspr(this.zylx).then(res => {
          this.sprData = res.data.data
          console.log(this.sprData)
        })
      },
      //获取危害辨识
      getfhyp() {
        getfhyp().then(res => {
          for (var i = 0; i < res.data.data.length; i++) {
            this.fhyp[i] =
              {
                label: res.data.data[i].dictValue,
                value: res.data.data[i].dictKey
              }
          }
          console.log(this.fhyp)
        })
      },
      //涉及特殊工种证书
      addZS(){
        if (this.form.zydwlb == '' || this.form.zydwlb == undefined) {
          this.$message.warning("请选择作业单位类别!");
          return;
        }
        this.chooseDialog = true;
      },
      // 确定选择证书
      confirmChooseZS(zsList) {
        console.log(zsList)
        this.zsData = zsList;
        this.closeChooseDialog();
      },
      // 关闭、取消选择证书
      closeChooseDialog() {
        this.selectedZS = [];
        this.chooseDialog = false;
      },
      //删除证书
      delZS(zsIndex){
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.zsData.splice(zsIndex, 1);
        });
      },
      // 获取应对事故类型列表
      getdhfs() {
        getdhfs().then(res => {
          this.cellChemicalsList = {};
          res.data.data.forEach(item => {
            this.cellChemicalsList[item.dictKey] = item.dictValue;
          });
          console.log(this.cellChemicalsList)
        })
      },
      // 显示应对事故类型列
      cellChemicals(row) {
        if(row.dhfs === undefined || typeof row.dhfs === "object") {
          return "";
        }
        var arr = row.dhfs.split(",");
        var faults = [];
        for(let i = 0 ; i < arr.length ; i++) {
          var fault = this.cellChemicalsList[arr[i]] === undefined ? arr[i] : this.cellChemicalsList[arr[i]];
          faults.push(fault);
        }
        console.log(faults)
        return faults.join("|");
      },
      // 上传附件前
      beforeUploadKJ(file) {
        this.isFailed = false;
        var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
        console.log(testmsg)
        const extension = testmsg === 'pdf'
        const extension2 = testmsg === 'mp4'
        const extension3 = testmsg === 'flv'
        var isLimit = this.fjFileList.length + 1 <= 1;
        if (!isLimit) {
          this.$message.warning("只能选择一个附件!");
          return isLimit;
        }else if(!extension && !extension2 && !extension3) {
          this.$message.warning('请上传 .pdf,.mp4,.flv 标准格式文件!');
          return this.isFailed;
        }
      },
      // 上传附件成功
      uploadKJSuccess(response, file, fileList) {
        if (response.code !== 200 || response.success !== true) {
          return;
        }
        this.fjFileList = fileList;
        this.form.fj = response.data.id;
        console.log(this.form.fj)
      },

      // 删除附件
      handleRemoveKJ(file, fileList) {
        this.fjFileList = fileList;
        this.form.fj = "";
      },
      // 选择部门
      getDept() {
        var tenantId = JSON.parse( localStorage.getItem("saber-tenantId") ).content;
        getDeptList(tenantId).then(res => {
          var n= res.data.data;
          this.deptData=n;
        }).then(() => {

        });
      },
      //安全措施
      getaqcs(){
        getzylxaqcs(this.zylx).then(res=>{
          const n=res.data.data
          n.forEach(aq=>aq.state=0)
          this.aqcsdata=n
        })
        console.log(this.aqcsdata)
      },
      //危害辨识措施
      funWh(label){
        if (this.form1!=null) {
          if (this.form.whbscs.indexOf(label) === -1) {
            this.form.whbscs+=label+':'+'\n'
          }else {
            var n=this.form.whbscs.slice(this.form.whbscs.indexOf(label),this.form.whbscs.indexOf('\n',this.form.whbscs.indexOf(label)+1))
            var s=this.form.whbscs.split(n+'\n')
            this.form.whbscs=s.join('')
          }
        }
      },
      //危害辨识
      getwhbs(){
        getYjsglxList().then(res=>{
          for (var i = 0; i < res.data.data.length; i++) {
            this.whbs[i]=
              {
                label : res.data.data[i].dictValue,
                value:res.data.data[i].dictKey
              }

          }

        })
        console.log(this.whbs)
      },
      //获取jsaName
      chooseControlJsa(list){
        this.jsaName=list[0].jsaNo
        this.jsaId=list[0].id
        this.cancelChooseControlJsa();
      },
      //取消JSA选择
      cancelChooseControlJsa(){
        this.dhjobJsaBox=false
      },
      //关闭JSA选择弹窗
      handleCloseChooseJsa(){
        this.cancelChooseControlJsa();
      },
      //打开JSA弹窗
      xzjsa(){
        this.dhjobJsaBox=true
      },

      rowSave(row, done, loading) {
        row.dhfs = typeof row.dhfs === "object" ? row.dhfs.join(",") : row.dhfs;
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style lang="scss" scpoed>
  .jsa_no{
    width: calc( 100% - 180px );
  }

  .avue-crud__dialog {
    .el-dialog__body {
      .el-form-item__label {
        width: 180px !important;
      }

      .avue-form__row {
        .el-form-item__content {
          margin-left: 180px !important;
        }
      }
    }
  }
</style>
